/**
 * 统一响应处理工具
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Object} options - 响应选项
 * @param {number} options.code - HTTP状态码
 * @param {string} options.message - 响应消息
 * @param {*} options.data - 响应数据
 * @param {boolean} options.success - 业务成功标识
 */
const { getLogger } = require('../logger');
const logger = getLogger('utils.response');
const sendResponse = (req, res, {
    code = 200, 
    message = 'Success', 
    data = null,
    success = null
}) => {
    // 参数校验
    if (!res || typeof res.status !== 'function') {
        logger.error('sendResponse: Invalid response object or status method not found');
        // 尝试使用logger输出或其他方式处理错误
        return;
    }
    
    const ok = code >= 200 && code < 300;
    const businessSuccess = success !== null ? success : ok;
    
    // 只有当请求头中存在X-Requested-Tooltype时才设置相应的响应头
    const response = res.status(code);
    
    if (req && req.headers && req.headers['x-requested-tooltype']) {
        response.set('X-Requested-Tooltype', req.headers['x-requested-tooltype']);
    }
    
    response.json({
        success: businessSuccess,
        code,
        message,
        data,
        timestamp: new Date().toISOString()
    });
};

/**
 * 成功响应
 */
const success = (req, res, message = '操作成功', data = null, code = 200) => {
    sendResponse(req, res, { code, message, data, success: true });
};

/**
 * 错误响应
 */
const error = (req, res, message = '操作失败', code = 400, data = null) => {
    sendResponse(req, res, { code, message, data, success: false });
};

/**
 * 服务器错误响应
 */
const serverError = (req, res, message = '服务器内部错误', data = null) => {
    sendResponse(req, res, { code: 500, message, data, success: false });
};

/**
 * 未找到资源响应
 */
const notFound = (req, res, message = '资源不存在', data = null) => {
    sendResponse(req, res, { code: 404, message, data, success: false });
};

/**
 * 未授权响应
 */
const unauthorized = (req, res, message = '未授权访问', data = null) => {
    sendResponse(req, res, { code: 401, message, data, success: false });
};

/**
 * 禁止访问响应
 */
const forbidden = (req, res, message = '禁止访问', data = null) => {
    sendResponse(req, res, { code: 403, message, data, success: false });
};

/**
 * 参数错误响应
 */
const badRequest = (req, res, message = '请求参数错误', data = null) => {
    sendResponse(req, res, { code: 400, message, data, success: false });
};

module.exports = {
    sendResponse,
    success,
    error,
    serverError,
    notFound,
    unauthorized,
    forbidden,
    badRequest
};